package com.itheima.health.utils;

import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.DelegatingPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@Setter
@Getter
public class PasswordUtil {

        private String forEncode = "bcrypt";
    /**
     * 详情看源码：DelegatingPasswordEncoder、BCryptPasswordEncoder、PasswordEncoderFactories(密码工厂)
     * @param idForEncode 传入要加密的算法
     * @param rawPassword 要加密的原始密码
     * @return 加密后的密码
     */
    public String encryptionPassword(String idForEncode,String rawPassword){
        /*
        bcrypt、ldap、MD4、MD5、noop(不加密)、pbkdf2、scrypt、SHA-1、SHA-256、sha256
         */

        if (!StringUtils.isEmpty(idForEncode)){
            forEncode = idForEncode;
        }
        Map<String, PasswordEncoder> map = new HashMap<>();
        map.put(forEncode,new BCryptPasswordEncoder());
        DelegatingPasswordEncoder encoder = new DelegatingPasswordEncoder(forEncode, map);
        String password = encoder.encode(rawPassword);
        log.info("[密码加密-使用的加密器&&加密后的密码] -idForEncode: {} - password: {}",forEncode,password);
        return password;
    }

}
